#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob
import logging as l
import optparse
import os
import os.path
import shutil
import subprocess
import sys
import tempfile

# Convert a timestamp into seconds.
def convertTime( timestampString ):
    parts = timestampString.split( ":" )
    if len( parts ) == 1:
        # Only seconds specified, add minutes to it.
        parts.insert( 0, "0" )
    if len( parts ) == 2:
        # No hours specified, add them to it.
        parts.insert( 0, "0" )
    return 3600 * int( parts[0] ) + 60 * int( parts[1] ) + int( parts[2] )

#~ 'Main'
if __name__ == "__main__":
    l.basicConfig( format = "%(asctime)-12s J264 Splitter: %(message)s",
                    datefmt = "%H:%M:%S" )
    # Check for options.
    if len( sys.argv ) != 2:
        print( """Usage: %s cutpoint-file\n
Where 'cutpoint-file' contains lines of data like follows:
quoted-path-to-video-file 1:22 48:56\n
I.e. line starts with a path to video file, followed by split area's
start and end points (time format is (HH:)MM:SS). All fields are
separated by space -> quote paths containing spaces. Line starting
with '#' indicates a comment.""" % os.path.split( sys.argv[0] )[1],
            file = sys.stderr )
        sys.exit( 2 )
    # Check for input file existence.
    cutpointFile = None
    try:
        cutpointFile = open( sys.argv[1], "r" )
    except:
        l.error( "Something backfired while opening the cutpoint file." )
        sys.exit( 1 )
    # Process file.
    lineCounter = 0
    for line in cutpointFile:
        lineCounter = lineCounter + 1
        line = line.strip()
        if len( line ) == 0 or line.startswith( "#" ):
            continue
        # Split by spaces and store two last items.
        parts = line.split( " " )
        endTime = convertTime( parts[-1] )
        startTime = convertTime( parts[-2] )
        # Replace start and end times with spaces in the originating line.
        line = line.replace( parts[-1], "" ).replace( parts[-2], "" )
        filename = line.strip().replace( '"', '' )
        outputDir, outputFilename = os.path.split( filename )
        outputFilename = "cut-" + outputFilename
        if len( outputDir ):
            outputFilename = outputDir + os.sep + outputFilename
        print( "MP4Box -splitx %d:%d -out \"%s\" \"%s\"" % ( startTime, endTime, outputFilename, filename ) )
